#!/usr/bin/env node

/**
 * 测试V2导入系统的完整数据流
 * 验证数据是否正确写入模拟数据库
 */

const path = require('path');
const fs = require('fs');

// 设置环境变量以使用模拟数据库
process.env.USE_MOCK_DB = 'true';
process.env.IMPORT_V2 = 'true';
process.env.NODE_ENV = 'development';

// 导入模拟数据库
const mockDB = require('./backend/src/config/mockDatabase');
const MenuImportService = require('./backend/src/services/MenuImportService');
const ImportJob = require('./backend/src/models/ImportJob');
const XLSX = require('xlsx');

async function testV2ImportFlow() {
  console.log('🧪 开始测试V2导入系统数据流...');
  
  try {
    // 1. 检查初始状态
    console.log('\n📊 检查初始模拟数据库状态:');
    const initialItems = await mockDB.query('SELECT * FROM menu_items');
    console.log(`初始菜单项数量: ${initialItems.length}`);
    initialItems.forEach(item => {
      console.log(`  - ${item.name} (ID: ${item.id})`);
    });
    
    // 2. 创建测试Excel文件
    console.log('\n📝 创建测试Excel文件...');
    const testFilePath = await createTestExcelFile();
    console.log(`测试文件已创建: ${testFilePath}`);
    
    // 3. 创建导入任务
    console.log('\n🔄 创建导入任务...');
    const job = await ImportJob.create({
      file_path: testFilePath,
      original_filename: 'test_v2_import.xlsx',
      file_size: fs.statSync(testFilePath).size,
      admin_id: 1,
      import_type: 'v2'
    });
    console.log(`任务已创建: ${job.job_id}`);
    
    // 4. 执行验证
    console.log('\n✅ 执行验证...');
    const importService = new MenuImportService();
    const validateResult = await importService.validateV2(job);
    console.log('验证结果:', validateResult.summary);
    
    if (validateResult.summary.error_count > 0) {
      console.log('❌ 验证失败，错误:', validateResult.errors);
      return;
    }
    
    // 5. 执行提交
    console.log('\n💾 执行提交...');
    const commitResult = await importService.commitV2(job, 'test-request');
    console.log('提交结果:', commitResult.summary);
    
    // 6. 检查提交后的数据库状态
    console.log('\n📊 检查提交后模拟数据库状态:');
    const finalItems = await mockDB.query('SELECT * FROM menu_items');
    console.log(`最终菜单项数量: ${finalItems.length}`);
    finalItems.forEach(item => {
      console.log(`  - ${item.name} (ID: ${item.id}, 分类: ${item.category_id})`);
    });
    
    // 7. 分析数据变化
    console.log('\n📈 数据变化分析:');
    const newItems = finalItems.filter(item => 
      !initialItems.some(initial => initial.id === item.id)
    );
    console.log(`新增菜单项数量: ${newItems.length}`);
    newItems.forEach(item => {
      console.log(`  + 新增: ${item.name} (ID: ${item.id})`);
    });
    
    // 8. 检查分类数据
    console.log('\n📂 检查分类数据:');
    const categories = await mockDB.query('SELECT * FROM menu_categories');
    console.log(`分类数量: ${categories.length}`);
    categories.forEach(cat => {
      console.log(`  - ${cat.name} (ID: ${cat.id})`);
    });
    
    console.log('\n✅ 测试完成!');
    
  } catch (error) {
    console.error('❌ 测试失败:', error);
    console.error(error.stack);
  }
}

async function createTestExcelFile() {
  const wb = XLSX.utils.book_new();
  
  // Dishes sheet - 使用正确的V2格式列名
  const dishesData = [
    ['dish_sku', 'dish_slug', 'name_zh', 'name_en', 'category', 'base_status', 'description_zh', 'description_en', 'ingredients_zh', 'ingredients_en', 'tags', 'popularity'],
    ['TEST-001', 'test-burger-001', '测试汉堡1', 'Test Burger 1', '汉堡', 'active', '美味测试汉堡', 'Delicious test burger', '牛肉,生菜', 'Beef, Lettuce', '热门,新品', '80'],
    ['TEST-002', 'test-drink-001', '测试饮料1', 'Test Drink 1', '饮料', 'active', '清爽测试饮料', 'Refreshing test drink', '水,糖', 'Water, Sugar', '清爽', '60']
  ];
  
  const dishesWS = XLSX.utils.aoa_to_sheet(dishesData);
  XLSX.utils.book_append_sheet(wb, dishesWS, 'Dishes');
  
  // Variants sheet - 使用正确的V2格式列名
  const variantsData = [
    ['dish_sku', 'name_zh', 'variant_code', 'variant_name', 'price', 'compare_at_price', 'is_default', 'stock'],
    ['TEST-001', '标准', 'STD-001', 'Standard', '15.99', '', 'true', '100'],
    ['TEST-002', '中杯', 'MED-001', 'Medium', '8.99', '', 'true', '50']
  ];
  const variantsWS = XLSX.utils.aoa_to_sheet(variantsData);
  XLSX.utils.book_append_sheet(wb, variantsWS, 'Variants');
  
  // Options sheet - 使用正确的V2格式列名
  const optionsData = [
    ['dish_sku', 'name_zh', 'group_code', 'group_name', 'required', 'value_code', 'value_name', 'price_delta'],
    ['TEST-001', '', 'SPICE', 'Spice Level', 'false', 'MILD', 'Mild', '0'],
    ['TEST-002', '', 'SWEET', 'Sweetness', 'false', 'NORMAL', 'Normal', '0']
  ];
  const optionsWS = XLSX.utils.aoa_to_sheet(optionsData);
  XLSX.utils.book_append_sheet(wb, optionsWS, 'Options');
  
  const filePath = path.join(__dirname, 'test_v2_import_flow.xlsx');
  XLSX.writeFile(wb, filePath);
  
  return filePath;
}

// 运行测试
if (require.main === module) {
  testV2ImportFlow().then(() => {
    console.log('\n🎯 测试脚本执行完成');
    process.exit(0);
  }).catch(error => {
    console.error('💥 测试脚本执行失败:', error);
    process.exit(1);
  });
}

module.exports = { testV2ImportFlow };